﻿using System.Collections.Generic;
using System.Linq;
using System.Drawing;

namespace Common
{
    public class Document
    {
        private Bitmap _bitmap;

        readonly List<Bitmap> _undoStack = new List<Bitmap>();
        readonly List<Bitmap> _redoStack = new List<Bitmap>();
        int _maxUndoCount;

        public Bitmap GetBitmap()
        {
            return _bitmap;
        }

        public void SetMaxUndoCount(int n)
        {
            _maxUndoCount = n;
        }

        public void SetBitmap(Bitmap bit)
        {
            if (_maxUndoCount > 0)
            {
                if (_undoStack.Count > _maxUndoCount)
                {
                    _undoStack.RemoveAt(0);
                }
                _undoStack.Add(_bitmap);
                _redoStack.Clear();
            }
            _bitmap = bit;
        }

        public void SetBitmapPreview(Bitmap bit)
        {
            _bitmap = bit;
        }

        public bool CanUndo()
        {
            return _undoStack.Count > 0;
        }

        public bool CanRedo()
        {
            return _redoStack.Count > 0;
        }

        public void Undo()
        {
            if (_undoStack.Count > 0)
            {
                _redoStack.Add(_bitmap);
                _bitmap = _undoStack.Last();
                _undoStack.RemoveAt(_undoStack.Count - 1);
            }
        }

        public void Redo()
        {
            if (_redoStack.Count > 0)
            {
                _undoStack.Add(_bitmap);
                _bitmap = _redoStack.Last();
                _redoStack.RemoveAt(_redoStack.Count - 1);
            }
        }

        public Document(string fileName)
        {
            var img = Image.FromFile(fileName);
            _bitmap = new Bitmap(img);
        }

        public Document()
        {
            _bitmap = new Bitmap(1, 1);
        }

        void Dispose()
        {
            _bitmap.Dispose();
        }

        void Save(string fileName)
        {
            _bitmap.Save(fileName);
        }
    }
}
